package com.imooc.controller;

import com.imooc.pojo.DbStu;
import com.imooc.pojo.bo.DbStuBO;
import com.imooc.service.StuService;
import com.imooc.utils.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("dbstu")
@Slf4j
public class DBStuController {
    // 注入Service
    @Autowired
    private StuService stuService;

    @GetMapping("{stuId}/get")
    public String getStu(@PathVariable("stuId") String stuId,
                         @RequestParam Integer id,
                         @RequestParam String name) {
        /**
         * @RequestParam: 用于获得URL中的请求参数，如果参数变量名保持一致，该注解可以省略
         */
        log.info("stuId = " + stuId);
        log.info("id = " + id);
        log.info("name = " + name);

        return "查询Stu";
    }

    @GetMapping("get")
    public JSONResult getStu(String stuId) {
        // 通过主键去查询
//        DbStu stu = stuService.queryById(stuId);
//        return JSONResult.ok(stu);
        // 条件查询
        List<DbStu> list = stuService.queryByCondition("abc", 1);   // 同时满足两个条件
        // 自定义SQL语句查询
        DbStu stu2 = stuService.queryByIdCustom(stuId);
//        return JSONResult.ok(list);
        return JSONResult.ok(stu2);
    }
    @GetMapping("create")
    public JSONResult createStu() {
        String sid = UUID.randomUUID().toString();
        DbStu stu = new DbStu();

        stu.setId(sid);
        stu.setName("IMOOC");
        stu.setSex(1);

        stuService.saveStu(stu);

        return JSONResult.ok();
    }
    @PostMapping("create2")
    public JSONResult createStu2(@Valid @RequestBody DbStuBO stuBO,
                                 BindingResult result) {
        // 判断 BindingResult 中是否包含一些错误的信息，如果有错误，则直接返回给前端
        if (result.hasErrors()) {
            Map<String, String> errorMap = getErrors(result);
            return JSONResult.errorMap(errorMap);
        }
        String sid = UUID.randomUUID().toString();
        DbStu stu = new DbStu();
        BeanUtils.copyProperties(stuBO, stu);

        stu.setId(sid);

        stuService.saveStu(stu);

        return JSONResult.ok();
    }
    /**
     * 获取BO业务对象的错误
     * @param result
     */
    public Map<String, String> getErrors(BindingResult result) {
        Map<String, String> errorMap = new HashMap<>(); // value是错误信息
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList) {
            // 获得检验发送错误的某个属性名称
            String field = error.getField();
            // 获得该属性发生错误的信息
            String msg = error.getDefaultMessage();
            errorMap.put(field, msg);
        }
        return errorMap;
    }
    @PutMapping("update")
    public String updateStu(@RequestBody Map<String, Object> map,
                            @RequestHeader("token") String token,
                            @CookieValue("clientId") String clientId,
                            HttpServletRequest request) {
        log.info("token = " + token);
        log.info("clientId = " + clientId);
        log.info("map = " + map.toString());

        String headerToken = request.getHeader("token");
        log.info("headerToken=" + headerToken);

        return "修改Stu";
    }
    @GetMapping("update")
    public JSONResult updateStu() {
        DbStu stu = new DbStu();
        stu.setId("1111");  // 主键
        stu.setName("已经修改的name");
        stu.setSex(2);

        stuService.updateStu(stu);

        return JSONResult.ok();
    }
//    @DeleteMapping("delete")
    @GetMapping("delete")
    public String deleteStu() {
        DbStu stu = new DbStu();
        stu.setId("111");   // 方式1：通过id

        stu.setSex(2);      // 方式2：通过条件匹配

        stu.setName("abc"); // 方式3：通过Example进行条件匹配

        stuService.deleteStu(stu);
        return "删除Stu";
    }
    @GetMapping("testTrans")
    public JSONResult testTrans() {
        stuService.testTrans();
        return JSONResult.ok();
    }
}
